<template>
  <div class="topbar-layout" :class="{ 'dark-mode': isDarkMode }">
    <!-- 顶部导航 -->
    <header class="top-header">
      <div class="header-left">
        <div class="logo-container">
          <img src="@/assets/logo.png" alt="Logo" class="logo" />
          <span class="app-name">ERP系统</span>
        </div>

        <!-- 一级菜单容器 -->
        <div class="menu-container" ref="menuContainerRef" @wheel="handleMenuScroll">
          <el-button
            v-show="showScrollButtons && canScrollLeft"
            class="scroll-button scroll-left"
            circle
            size="small"
            @click="scrollMenu(-200)"
          >
            <el-icon><ArrowLeft /></el-icon>
          </el-button>

          <div class="menu-wrapper" ref="menuWrapperRef">
            <el-menu
              :default-active="activeModule"
              mode="horizontal"
              class="top-menu"
              @select="handleModuleSelect"
            >
              <el-menu-item v-for="item in topMenuItems" :key="item.path" :index="item.path">
                <el-icon><component :is="item.icon" /></el-icon>
                <span>{{ item.title }}</span>
              </el-menu-item>
            </el-menu>
          </div>

          <el-button
            v-show="showScrollButtons && canScrollRight"
            class="scroll-button scroll-right"
            circle
            size="small"
            @click="scrollMenu(200)"
          >
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
      </div>

      <div class="header-right">
        <el-tooltip content="全局搜索 (Ctrl+/)">
          <el-button circle @click="showSearchDialog">
            <el-icon><Search /></el-icon>
          </el-button>
        </el-tooltip>
        <!-- 消息通知 -->
        <NotificationCenter />
        <el-tooltip content="导航设置">
          <el-button circle @click="showNavigationSettings">
            <el-icon><Setting /></el-icon>
          </el-button>
        </el-tooltip>
        <el-dropdown @command="handleUserCommand">
          <div class="user-info">
            <el-avatar :size="32" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            <span class="username">管理员</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                系统设置
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主体内容 -->
    <div class="main-wrapper">
      <!-- 左侧二级菜单 -->
      <aside class="sub-sidebar" v-if="currentSubMenus.length > 0">
        <el-scrollbar class="menu-scrollbar">
          <el-menu
            :default-active="activeMenu"
            :collapse="false"
            :unique-opened="true"
            router
          >
            <template v-for="item in currentSubMenus" :key="item.path">
              <!-- 有子菜单 -->
              <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.path">
                <template #title>
                  <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
                  <span>{{ item.title }}</span>
                </template>
                <el-menu-item
                  v-for="child in item.children"
                  :key="child.path"
                  :index="child.path"
                >
                  {{ child.title }}
                </el-menu-item>
              </el-sub-menu>
              <!-- 无子菜单 -->
              <el-menu-item v-else :index="item.path">
                <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
                <template #title>{{ item.title }}</template>
              </el-menu-item>
            </template>
          </el-menu>
        </el-scrollbar>
      </aside>

      <!-- 右侧内容区 -->
      <div class="content-wrapper" :class="{ 'full-width': currentSubMenus.length === 0 }">
        <!-- 面包屑和操作栏 -->
        <div class="content-header">
          <el-breadcrumb v-if="showBreadcrumb" class="breadcrumb" separator="/">
            <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index" :to="item.path">
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>

          <div class="header-actions">
            <el-tooltip content="刷新">
              <el-button circle size="small" @click="refresh">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="全屏">
              <el-button circle size="small" @click="toggleFullscreen">
                <el-icon><FullScreen /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>

        <!-- 标签页 -->
        <div v-if="showTabs" class="tabs-container">
          <el-scrollbar>
            <div class="tabs-wrapper">
              <div
                v-for="tab in openedTabs"
                :key="tab.path"
                class="tab-item"
                :class="{ active: tab.path === activeTab }"
                @click="handleTabClick(tab)"
              >
                <span class="tab-title">{{ tab.title }}</span>
                <el-icon class="tab-close" @click.stop="removeTab(tab.path)">
                  <Close />
                </el-icon>
              </div>
            </div>
          </el-scrollbar>
          <el-dropdown @command="handleTabsCommand" trigger="click">
            <el-button size="small" text class="tabs-more">
              <el-icon><MoreFilled /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="closeOther">关闭其他</el-dropdown-item>
                <el-dropdown-item command="closeLeft">关闭左侧</el-dropdown-item>
                <el-dropdown-item command="closeRight">关闭右侧</el-dropdown-item>
                <el-dropdown-item command="closeAll">关闭全部</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 页面内容 -->
        <main class="page-content" :class="{ 'compact-mode': compactMode }">
          <router-view v-slot="{ Component }">
            <transition name="fade-slide" mode="out-in">
              <keep-alive :include="cachedViews">
                <component :is="Component" :key="$route.fullPath" />
              </keep-alive>
            </transition>
          </router-view>
        </main>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavigationStore } from '@/stores/navigation'
import { useUserStore } from '@/stores/user'
import { menuData } from '@/config/menu'
import NotificationCenter from '@/components/common/NotificationCenter.vue'

const route = useRoute()
const router = useRouter()
const navigationStore = useNavigationStore()

// 响应式数据
const activeModule = ref('')
const activeMenu = computed(() => route.path)
const activeTab = ref(route.path)

// 菜单滚动相关
const menuContainerRef = ref(null)
const menuWrapperRef = ref(null)
const canScrollLeft = ref(false)
const canScrollRight = ref(false)
const showScrollButtons = ref(false)

// Store数据
const showBreadcrumb = computed(() => navigationStore.settings.showBreadcrumb)
const showTabs = computed(() => navigationStore.settings.showTabs)
const compactMode = computed(() => navigationStore.settings.compactMode)
const isDarkMode = computed(() => navigationStore.settings.darkMode)
const openedTabs = computed(() => navigationStore.openedTabs)

// 顶部一级菜单
const topMenuItems = ref(menuData)

// 当前二级菜单
const currentSubMenus = computed(() => {
  const currentModule = topMenuItems.value.find(item => item.path === activeModule.value)
  return currentModule?.children || []
})

// 面包屑
const breadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    path: item.path,
    title: item.meta.title
  }))
})

// 缓存的视图
const cachedViews = computed(() => {
  return openedTabs.value.filter(tab => tab.keepAlive).map(tab => tab.name)
})

// 方法
const handleModuleSelect = (path) => {
  activeModule.value = path
  navigationStore.setActiveModule(path)

  // 如果该模块有子菜单，跳转到第一个子菜单
  const module = topMenuItems.value.find(item => item.path === path)
  if (module?.children && module.children.length > 0) {
    const firstChild = module.children[0]
    if (firstChild.children && firstChild.children.length > 0) {
      router.push(firstChild.children[0].path)
    } else {
      router.push(firstChild.path)
    }
  } else {
    router.push(path)
  }
}

const showSearchDialog = () => {
  console.log('Show search dialog')
}

const showNavigationSettings = () => {
  window.dispatchEvent(new CustomEvent('show-navigation-settings'))
}

const handleUserCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
      ElMessage.success('已退出登录')
    }).catch(() => {})
  } else if (command === 'profile') {
    router.push('/system/user-settings')
  } else if (command === 'settings') {
    router.push('/system/settings')
  }
}

const refresh = () => {
  router.go(0)
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const removeTab = (targetPath) => {
  const tabs = openedTabs.value
  const currentIndex = tabs.findIndex(tab => tab.path === targetPath)

  if (currentIndex > -1) {
    navigationStore.removeTab(targetPath)

    if (targetPath === route.path) {
      const nextTab = tabs[currentIndex + 1] || tabs[currentIndex - 1]
      if (nextTab) {
        router.push(nextTab.path)
      } else {
        router.push('/')
      }
    }
  }
}

const handleTabClick = (tab) => {
  router.push(tab.path)
}

const handleTabsCommand = (command) => {
  const currentPath = route.path
  const currentIndex = openedTabs.value.findIndex(tab => tab.path === currentPath)

  if (command === 'closeOther') {
    const currentTab = openedTabs.value.find(tab => tab.path === currentPath)
    navigationStore.clearTabs()
    if (currentTab) {
      navigationStore.addTab(currentTab)
    }
  } else if (command === 'closeLeft') {
    const tabs = openedTabs.value.slice(0, currentIndex)
    tabs.forEach(tab => navigationStore.removeTab(tab.path))
  } else if (command === 'closeRight') {
    const tabs = openedTabs.value.slice(currentIndex + 1)
    tabs.forEach(tab => navigationStore.removeTab(tab.path))
  } else if (command === 'closeAll') {
    navigationStore.clearTabs()
    router.push('/')
  }
}

// 根据当前路由确定激活的模块
const updateActiveModule = () => {
  const path = route.path
  for (const module of topMenuItems.value) {
    if (path.startsWith(module.path)) {
      activeModule.value = module.path
      navigationStore.setActiveModule(module.path)
      break
    }
  }
}

// 添加当前标签
const addCurrentTab = () => {
  if (route.meta.title) {
    navigationStore.addTab({
      path: route.path,
      title: route.meta.title,
      name: route.name,
      keepAlive: route.meta.keepAlive || false
    })
  }
}

// 菜单滚动处理
const handleMenuScroll = (e) => {
  e.preventDefault()
  const delta = e.deltaY || e.deltaX
  if (menuWrapperRef.value) {
    menuWrapperRef.value.scrollLeft += delta
    updateScrollButtons()
  }
}

const scrollMenu = (distance) => {
  if (menuWrapperRef.value) {
    menuWrapperRef.value.scrollBy({
      left: distance,
      behavior: 'smooth'
    })
    setTimeout(updateScrollButtons, 300)
  }
}

const updateScrollButtons = () => {
  if (!menuWrapperRef.value) return

  const wrapper = menuWrapperRef.value
  const scrollLeft = wrapper.scrollLeft
  const scrollWidth = wrapper.scrollWidth
  const clientWidth = wrapper.clientWidth

  // 判断是否需要显示滚动按钮
  showScrollButtons.value = scrollWidth > clientWidth

  // 更新按钮状态
  canScrollLeft.value = scrollLeft > 0
  canScrollRight.value = scrollLeft < scrollWidth - clientWidth - 1
}

const checkMenuOverflow = () => {
  nextTick(() => {
    updateScrollButtons()
  })
}

// 监听窗口大小变化
let resizeObserver = null

// 生命周期
onMounted(() => {
  navigationStore.loadFromServer()
  updateActiveModule()
  addCurrentTab()

  // 检查菜单溢出
  checkMenuOverflow()

  // 添加滚动监听
  if (menuWrapperRef.value) {
    menuWrapperRef.value.addEventListener('scroll', updateScrollButtons)
  }

  // 监听窗口大小变化
  resizeObserver = new ResizeObserver(() => {
    checkMenuOverflow()
  })

  if (menuContainerRef.value) {
    resizeObserver.observe(menuContainerRef.value)
  }
})

onUnmounted(() => {
  if (menuWrapperRef.value) {
    menuWrapperRef.value.removeEventListener('scroll', updateScrollButtons)
  }
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
})

// 监听路由变化
watch(() => route.path, () => {
  updateActiveModule()
  addCurrentTab()
  activeTab.value = route.path
})
</script>

<style scoped>
.topbar-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
}

.top-header {
  height: 60px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 24px;
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-right: 24px;
  border-right: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.logo {
  height: 20px;
}

.app-name {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

/* 菜单容器 */
.menu-container {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
  min-width: 0;
  overflow: hidden;
}

.menu-wrapper {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.menu-wrapper::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.top-menu {
  border: none;
  background: transparent;
  display: inline-flex;
  white-space: nowrap;
}

.top-menu :deep(.el-menu-item) {
  height: 60px;
  line-height: 60px;
  border-bottom: 2px solid transparent;
  flex-shrink: 0;
}

.top-menu :deep(.el-menu-item.is-active) {
  border-bottom-color: var(--el-color-primary);
  background: transparent;
}

/* 滚动按钮 */
.scroll-button {
  position: absolute;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.scroll-button:hover {
  background: white;
  transform: scale(1.1);
}

.scroll-left {
  left: 0;
}

.scroll-right {
  right: 0;
}

.dark-mode .scroll-button {
  background: rgba(31, 31, 31, 0.9);
  color: #e4e7ed;
}

.dark-mode .scroll-button:hover {
  background: #2a2a2a;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-badge {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.user-info:hover {
  background: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #303133;
}

.main-wrapper {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sub-sidebar {
  width: 220px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  overflow: hidden;
}

.menu-scrollbar {
  height: 100%;
}

.sub-sidebar .el-menu {
  border: none;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin-left: 0;
  transition: margin-left 0.3s ease;
}

.content-wrapper.full-width {
  margin-left: 0;
}

.content-header {
  background: #fff;
  padding: 12px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.breadcrumb {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.tabs-container {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 16px;
  display: flex;
  align-items: center;
  height: 40px;
}

.tabs-container :deep(.el-scrollbar) {
  flex: 1;
}

.tabs-wrapper {
  display: flex;
  gap: 4px;
  padding: 4px 0;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.tab-item:hover {
  background: #e4e7ed;
}

.tab-item.active {
  background: var(--el-color-primary);
  color: white;
}

.tab-title {
  font-size: 13px;
}

.tab-close {
  font-size: 12px;
  opacity: 0.6;
  transition: opacity 0.3s ease;
}

.tab-close:hover {
  opacity: 1;
}

.tab-item.active .tab-close {
  color: white;
}

.tabs-more {
  margin-left: 8px;
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
  background: #f0f2f5;
  height: 0; /* 触发flex子元素的overflow */
}

.page-content.compact-mode {
  padding: 12px;
}

/* 过渡动画 */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 暗黑模式 */
.dark-mode .top-header {
  background: #1f1f1f;
  color: #e4e7ed;
}

.dark-mode .sub-sidebar {
  background: #1f1f1f;
  border-right-color: #3a3a3a;
}

.dark-mode .content-header {
  background: #1f1f1f;
  border-bottom-color: #3a3a3a;
}

.dark-mode .tabs-container {
  background: #1f1f1f;
  border-bottom-color: #3a3a3a;
}

.dark-mode .page-content {
  background: #141414;
}

.dark-mode .tab-item {
  background: #2a2a2a;
  color: #e4e7ed;
}

.dark-mode .tab-item:hover {
  background: #3a3a3a;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .menu-container {
    display: none;
  }

  .sub-sidebar {
    width: 180px;
  }
}

@media (max-width: 768px) {
  .logo-container {
    padding-right: 12px;
  }

  .app-name {
    display: none;
  }

  .sub-sidebar {
    position: fixed;
    left: -220px;
    top: 60px;
    bottom: 0;
    z-index: 999;
    transition: left 0.3s ease;
  }

  .sub-sidebar.show {
    left: 0;
  }
}

/* 菜单项样式优化 */
.top-menu :deep(.el-menu-item) {
  padding: 0 20px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.top-menu :deep(.el-menu-item .el-icon) {
  margin-right: 0;
}
</style>
